//
//  OAuthViewController.swift
//  Weibo19
//
//  Created by 城 on 15/11/9.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    
 
    //定义一个webView属性
    let webView = UIWebView()
    
    
    //MARK: 监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = '469770143@qq.com' , document.getElementById('passwd').value = '17v77.com';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        //加载网页
        loadOauthPage()
    }
    
    
    
    private func loadOauthPage() {
        //拼接字符串
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    //
    private func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
    
}

//专门处理 webView所有的协议方法
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    

    //协议方法 如果返回 bool  一般表示 如果为true  表示当前对象可以正常 工作  否则就不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
  print(request.URL?.absoluteString)
            return false
        }
        
        //是网页请求页面 或者请求授权页面
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        //程序走到这里  一定包含了  回调的url
        guard let query = request.URL?.query else {
            print(request.URL?.query)
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
    
 
        
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
           self.dismissViewControllerAnimated(true, completion: nil)
            SVProgressHUD.dismiss()
        }
        return false
        
    }
    

}